﻿using LanguagePolish.Base;
using LanguagePolish.EntityModel;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Input;

namespace LanguagePolish.Controls
{
    class MonthCalendarViewModel : BaseViewModel
    {
        private static readonly ILessonsProvider FakeLessonsProvider = new FakeLessonsProvider();

        private readonly MonthCalendarModel model;
        
        private ILessonsProvider lessonsProvider;
        public ILessonsProvider LessonsProvider 
        {
            get 
            {
                if (lessonsProvider == null)
                    return FakeLessonsProvider;
                return lessonsProvider;
            }
            set
            {
                lessonsProvider = value;
                ReloadLessons();
            }
        }

        /// <summary>
        /// Текущий месяц в строковом представлении
        /// </summary>
        public string CurrentMonthStr { get { return GlobalSettings.Months[model.CurrentMonth - 1]; } }

        /// <summary>
        /// Текущий месяц
        /// </summary>
        public int CurrentMonth { get { return model.CurrentMonth; } }

        /// <summary>
        /// Текущий год
        /// </summary>
        public int CurrentYear { get { return model.CurrentYear; } }

        IEnumerable<Lesson> lessons;
        public IEnumerable<Lesson> CurrentLessons { get { return lessons; } }

        public ICommand PrevMonth { get; private set; }
        public ICommand NextMonth { get; private set; }

        public MonthCalendarViewModel()
        {
            model = new MonthCalendarModel();
            PrevMonth = new RelayCommand(DecrementMonth);
            NextMonth = new RelayCommand(IncrementMonth);
            ReloadLessons();
        }

        private void IncrementMonth()
        {
            model.IncrementMonth();
            OnPropertyChanged("CurrentMonth");
            OnPropertyChanged("CurrentMonthStr");
            OnPropertyChanged("CurrentYear");
            ReloadLessons();
        }

        private void DecrementMonth()
        {
            model.DecrementMonth();
            OnPropertyChanged("CurrentMonth");
            OnPropertyChanged("CurrentMonthStr");
            OnPropertyChanged("CurrentYear");
            ReloadLessons();
        }

        public void ReloadLessons()
        {
            DateTime from = new DateTime(CurrentYear, CurrentMonth, 1);
            int daysInMonth = DateTime.DaysInMonth(CurrentYear, CurrentMonth);
            DateTime to = new DateTime(CurrentYear, CurrentMonth, daysInMonth);
            lessons = LessonsProvider.GetLessons(from, to);
            OnPropertyChanged("CurrentLessons");
        }
    }
}
